using System;
using System.Linq;
using JNPF.Utils;
using System.Threading.Tasks;
using JNPF.Data;
using JNPF.Data.Util;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using JNPF.Basics.Models;
using System.Text;
using System.Data.Common;

namespace JNPF.Basics.Logic
{
    public class CustomerbaseService : DataFactory, CustomerbaseIService
    {
        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        public async Task<CustomerbaseEntity> GetInfo(int id)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<CustomerbaseEntity>(m => m.Id == id);
            }
        }
        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="phone">主键id</param>
        /// <returns></returns>
        public async Task<CustomerbaseEntity> GetInfoByPhone(string phone)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<CustomerbaseEntity>(m => m.MobilePhone == phone);
            }
        }
        /// <summary>
        ///根据用户名称 获取信息
        /// </summary>
        /// <param name="customerName">用户名称</param>
        /// <returns></returns>
        public async Task<CustomerbaseEntity> GetInfo(string customerName)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<CustomerbaseEntity>(m => m.CustomerName == customerName && m.DeleteMark == 0);
            }
        }

        /// <summary>
        ///根据用户名称 获取信息
        /// </summary>
        /// <param name="socialCreditCode">统一信用代码</param>
        /// <returns></returns>
        public async Task<CustomerbaseEntity> GetInfoBySocialCreditCode(string socialCreditCode)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<CustomerbaseEntity>(m => m.SocialCreditCode == socialCreditCode && m.DeleteMark == 0);
            }
        }


        /// <summary>
        /// 列表（分页）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<CustomerbaseEntity>> GetPageList(CustomerbaseListQueryInput input)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<CustomerbaseEntity>();
                var queryParam = input.queryJson.ToObject();
                //查询客户名称
                if (!string.IsNullOrEmpty(input.customerName))
                {
                    queryWhere = queryWhere.And(m => m.CustomerName.Contains(input.customerName));
                }
                //查询统一社会信用代码
                if (!string.IsNullOrEmpty(input.socialCreditCode))
                {
                    queryWhere = queryWhere.And(m => m.SocialCreditCode.Contains(input.socialCreditCode));
                }
                if (!string.IsNullOrEmpty(input.partnerUserId))
                {
                    queryWhere = queryWhere.And(m => m.PartnerUserId == input.partnerUserId);
                }

                if (!string.IsNullOrEmpty(input.userId))
                {
                    queryWhere = queryWhere.And(m => m.PartnerUserId == input.partnerUserId);
                }


                //查询统一社会信用代码
                if (!string.IsNullOrEmpty(input.selectKey))
                {
                    queryWhere = queryWhere.And(m => m.SocialCreditCode.Contains(input.selectKey)).Or(m => m.CustomerName.Contains(input.selectKey));
                }
                if (input.isHideName)
                {
                    //大厅脱敏字段不能为空
                    queryWhere = queryWhere.And(m => !string.IsNullOrEmpty(m.HideName));
                }


                if (input.type.HasValue)
                {
                    queryWhere = queryWhere.And(m => m.Type == input.type);
                }


                queryWhere = queryWhere.And(m => m.DeleteMark == 0);
                return await db.GetIQueryable<CustomerbaseEntity>().Where(queryWhere).GetPageResultAsync(input);
            }
        }

        public async Task<PageResult<CustomerbaseListOutput>> GetPageList(CustomerbaseListQueryInput input, string userId)
        {

            using (var db = this.Basic)
            {
                var parameters = new List<DbParameter>();
                var dbSql = new StringBuilder();
                dbSql.Append(@"SELECT
                                 DISTINCT b.F_ID,b.F_CustomerName,b.F_SocialCreditCode,b.F_LegalRepresentative,b.F_EstablishmentDate,b.F_CreatorTime,b.F_Type
                                FROM
	                                jiushi_customerbase b
	                                LEFT JOIN jiushi_customeruser u ON u.F_CustomerId = b.F_ID
	                                LEFT JOIN jiushi_customerloan l ON l.F_CustomerId = b.F_ID 
                                WHERE  
	                                b.F_DeleteMark =0");

                UserInfo userInfo = UserProvider.Instance.Get();


                dbSql.Append(" AND b.F_CreatorUserId = @userId");
                parameters.Add(DataHelper.CreateParameter("@userId", userInfo.UserId));


                input.sidx = "F_CreatorTime";
                return await PageHelper.GetPageResultAsync<CustomerbaseListOutput>(db, input, dbSql.ToString(), parameters.ToArray());





            }
        }



        /// <summary>
        /// 企业用户  ===  手机号码对应起来的 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<CustomerbaseListOutput>> GetBusPageList(CustomerbaseListQueryInput input)
        {

            UserInfo userInfo = UserProvider.Instance.Get();
            input.sidx = "F_CreatorTime";
            using (var db = this.Basic)
            {
                var parameters = new List<DbParameter>();
                var dbSql = new StringBuilder();
                dbSql.Append(@"SELECT
	cus.F_ID,
	cus.F_CustomerName,
	cus.F_HonoraryTitleField,
	cus.F_BusinessId,
	cus.F_BasicAccountInfo,
	cus.F_BasicAccountInfoBusinessId,
	cus.F_ActualBusinessPreArea,
	cus.F_MainProduct,
	cus.F_MainProductBusinessId,
	cus.F_MainProductProcess,
	cus.F_MainProductProcessBusinessId,
	cus.F_MobilePhone,
	cus.F_SocialCreditCode,
	cus.F_EstablishmentDate,
	cus.F_LegalRepresentative,
	cus.F_RegisteredCapital,
	cus.F_RegisteredAddress,
	cus.F_CustomerProfile,
	cus.F_IndustryClassification,
	cus.F_ActualBusinessAddress,
	cus.F_ActualControllerID,
	cus.F_MainProducts,
	cus.F_InsuredEmployeeCount,
	cus.F_NonInsuredEmployeeCount,
	cus.F_PartTimeEmployeeCount,
	cus.F_CurrentState,
	cus.F_PartnerUserId,
	cus.F_PartnerUserRealName,
	cus.F_SortCode,
	cus.F_EnabledMark,
	cus.F_CreatorTime,
	cus.F_CreatorUser,
	cus.F_CreatorUserId,
	cus.F_LastModifyTime,
	cus.F_LastModifyUserId,
	cus.F_DeleteMark,
	cus.F_DeleteTime,
	cus.F_DeleteUserId,
	cus.F_HideName,
	cus.F_ComConfig,
	cus.F_LinkName,
    cus.F_Type,
	buser.F_RealName userName 
FROM
	jiushi_customerbase cus
	INNER JOIN jiushi_customeruser cususer ON cususer.F_CustomerId = cus.F_ID
	INNER JOIN base_user buser ON buser.F_ID = cususer.F_UserId 
WHERE
	1 = 1 
	AND cususer.F_Type = 1 
	AND cus.F_DeleteMark = 0");



                dbSql.Append("  and cus.F_MobilePhone = @mobilePhone");
                parameters.Add(DataHelper.CreateParameter("@mobilePhone", userInfo.UserAccount));

                return await PageHelper.GetPageResultAsync<CustomerbaseListOutput>(db, input, dbSql.ToString(), parameters.ToArray());
            }

        }

        /// <summary>
        /// 客户经理列表（分页）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<CustomerbaseListOutput>> GetCuseBusList(CustomerbaseListQueryInput input)
        {

            UserInfo userInfo = UserProvider.Instance.Get();
            input.sidx = "F_CreatorTime";
            using (var db = this.Basic)
            {
                var parameters = new List<DbParameter>();
                var dbSql = new StringBuilder();
                dbSql.Append(@"SELECT
	cus.F_ID,
	cus.F_CustomerName,
	cus.F_HonoraryTitleField,
	cus.F_BusinessId,
	cus.F_BasicAccountInfo,
	cus.F_BasicAccountInfoBusinessId,
	cus.F_ActualBusinessPreArea,
	cus.F_MainProduct,
	cus.F_MainProductBusinessId,
	cus.F_MainProductProcess,
	cus.F_MainProductProcessBusinessId,
	cus.F_MobilePhone,
	cus.F_SocialCreditCode,
	cus.F_EstablishmentDate,
	cus.F_LegalRepresentative,
	cus.F_RegisteredCapital,
	cus.F_RegisteredAddress,
	cus.F_CustomerProfile,
	cus.F_IndustryClassification,
	cus.F_ActualBusinessAddress,
	cus.F_ActualControllerID,
	cus.F_MainProducts,
	cus.F_InsuredEmployeeCount,
	cus.F_NonInsuredEmployeeCount,
	cus.F_PartTimeEmployeeCount,
	cus.F_CurrentState,
	cus.F_PartnerUserId,
	cus.F_PartnerUserRealName,
	cus.F_SortCode,
	cus.F_EnabledMark,
	cus.F_CreatorTime,
	cus.F_CreatorUser,
	cus.F_CreatorUserId,
	cus.F_LastModifyTime,
	cus.F_LastModifyUserId,
	cus.F_DeleteMark,
	cus.F_DeleteTime,
	cus.F_DeleteUserId,
	cus.F_HideName,
	cus.F_ComConfig,
	cus.F_LinkName,
    cus.F_Type
FROM
	jiushi_customerbase cus
	INNER JOIN jiushi_Customerloan loan on  loan.F_CustomerId = cus.F_ID
	INNER JOIN jiushi_customeruser cususer ON cususer.F_CustomerId = cus.F_ID
	INNER JOIN base_user buser ON buser.F_ID = cususer.F_UserId 
WHERE
	1 = 1 
	AND cususer.F_Type = 1 
	AND cus.F_DeleteMark = 0");
                dbSql.Append(" and loan.F_BankUserId    = @UserId");
                parameters.Add(DataHelper.CreateParameter("@UserId", userInfo.UserId));
                return await PageHelper.GetPageResultAsync<CustomerbaseListOutput>(db, input, dbSql.ToString(), parameters.ToArray());
            }

        }


        /// <summary>
        /// 信贷管家   列表（分页）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<CustomerbaseListOutput>> GetPagCuseList(CustomerbaseListQueryInput input)
        {

            UserInfo userInfo = UserProvider.Instance.Get();
            input.sidx = "F_CreatorTime";
            using (var db = this.Basic)
            {
                var parameters = new List<DbParameter>();
                var dbSql = new StringBuilder();
                dbSql.Append(@"SELECT
	                    cus.F_ID,
	                    cus.F_CustomerName,
	                    cus.F_HonoraryTitleField,
	                    cus.F_BusinessId,
	                    cus.F_BasicAccountInfo,
	                    cus.F_BasicAccountInfoBusinessId,
	                    cus.F_ActualBusinessPreArea,
	                    cus.F_MainProduct,
	                    cus.F_MainProductBusinessId,
	                    cus.F_MainProductProcess,
	                    cus.F_MainProductProcessBusinessId,
	                    cus.F_MobilePhone,
	                    cus.F_SocialCreditCode,
	                    cus.F_EstablishmentDate,
	                    cus.F_LegalRepresentative,
	                    cus.F_RegisteredCapital,
	                    cus.F_RegisteredAddress,
	                    cus.F_CustomerProfile,
	                    cus.F_IndustryClassification,
	                    cus.F_ActualBusinessAddress,
	                    cus.F_ActualControllerID,
	                    cus.F_MainProducts,
	                    cus.F_InsuredEmployeeCount,
	                    cus.F_NonInsuredEmployeeCount,
	                    cus.F_PartTimeEmployeeCount,
	                    cus.F_CurrentState,
	                    cus.F_PartnerUserId,
	                    cus.F_PartnerUserRealName,
	                    cus.F_SortCode,
	                    cus.F_EnabledMark,
	                    cus.F_CreatorTime,
	                    cus.F_CreatorUser,
	                    cus.F_CreatorUserId,
	                    cus.F_LastModifyTime,
	                    cus.F_LastModifyUserId,
	                    cus.F_DeleteMark,
	                    cus.F_DeleteTime,
	                    cus.F_DeleteUserId,
	                    cus.F_HideName,
	                    cus.F_ComConfig,
	                    cus.F_LinkName,
                        cus.F_Type
                    FROM
	                    jiushi_customerbase cus
	                    INNER JOIN jiushi_customeruser cususer ON cususer.F_CustomerId = cus.F_ID
	                    INNER JOIN base_user buser ON buser.F_ID = cususer.F_UserId 
                    WHERE
	                    1 = 1 
	                    AND cususer.F_Type = 1 
	                    AND cus.F_DeleteMark = 0
	");
                dbSql.Append(" and  cususer.F_UserId = @UserId");
                parameters.Add(DataHelper.CreateParameter("@UserId", userInfo.UserId));
                return await PageHelper.GetPageResultAsync<CustomerbaseListOutput>(db, input, dbSql.ToString(), parameters.ToArray());
            }

        }






        /// <summary>
        /// 创建信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Create(CustomerbaseEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.InsertAsync(entity);
            }
        }


        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> NewneedsCreate(NewneedsEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.InsertAsync(entity);
            }

        }


        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="baseEntity">用户信息</param>
        /// <param name="entity">实体对象</param>
        /// <param name="userRelationList">用户关系</param>
        /// <returns></returns>
        public async Task Create(CustomerbaseEntity baseEntity, UserEntity entity, List<UserRelationEntity> userRelationList)
        {
            using (var db = this.Basic)
            {
                await db.BeginTransactionAsync();


                await db.UpdateAsync(baseEntity);

                await db.InsertAsync(entity);

                await db.InsertAsync(userRelationList);

                await db.CommitTransactionAsync();
            }
        }


        /// <summary>
        /// 更新信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Update(CustomerbaseEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.UpdateAsync(entity);
            }
        }

        /// <summary>
        /// 录入首页推送信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> newneedsEntityInsert(NewneedsEntity newneedsEntity)
        {
            using (var db = this.Basic)
            {
                return await db.InsertAsync(newneedsEntity);
            }
        }


        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Delete(CustomerbaseEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.DeleteAsync(entity);
            }
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<List<CustomerbaseEntity>> GetList(CustomerbaseListQueryInput input)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<CustomerbaseEntity>();
                //查询客户名称
                if (!string.IsNullOrEmpty(input.customerName))
                {
                    queryWhere = queryWhere.And(m => m.CustomerName.Contains(input.customerName));
                }
                //查询统一社会信用代码
                if (!string.IsNullOrEmpty(input.socialCreditCode))
                {
                    queryWhere = queryWhere.And(m => m.SocialCreditCode.Contains(input.socialCreditCode));
                }

                queryWhere = queryWhere.And(m => m.DeleteMark == 0);

                return await db.GetIQueryable<CustomerbaseEntity>().Where(queryWhere).ToListAsync();
            }
        }


    }
}